//
//  NSMutableData+BufferHandler.m
//  LazyHome
//
//  Created by yh on 2018/4/17.
//  Copyright © 2018年 yh. All rights reserved.
//

#import "NSMutableData+BufferHandler.h"
#import <objc/runtime.h>
#include "GBNumber.h"



@implementation NSData(BufferHandler)
- (char)toChar{
    char i;
    [self getBytes: &i length: sizeof(i)];
    return i;
}
- (unsigned char)toUChar{
    unsigned char i;
    [self getBytes: &i length: sizeof(i)];
    return i;
}

- (short)toShort{
    short i;
    [self getBytes: &i length: sizeof(i)];
    return i;
}
- (unsigned short)toUShort{
    unsigned short i;
    [self getBytes: &i length: sizeof(i)];
    return ushort_swap(i);
}

- (int)toInt{
    int i;
    [self getBytes: &i length: sizeof(i)];
    return i;
}
- (unsigned int)toUInt{
    unsigned int i;
    [self getBytes: &i length: sizeof(i)];
    return i;
}

+ (NSData *)dataWithUchar:(unsigned char)dat{
    NSData *data = [NSData dataWithBytes: &dat length: sizeof(dat)];
    return data;
}

+ (NSData *)dataWithUshort:(unsigned short)dat{
    NSData *data = [NSData dataWithBytes: &dat length: sizeof(dat)];
    return data;
}

@end




@interface NSMutableData()

@end
static char flashColorKey;
@implementation NSMutableData(BufferHandler)
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.handle_index = @(0);
    }
    return self;
}

- (void)setHandle_index:(NSNumber *)handle_index{
    objc_setAssociatedObject(self, &flashColorKey, handle_index, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSNumber *)handle_index{
    return  objc_getAssociatedObject(self, &flashColorKey);
}

- (NSData *)readDataWithLength:(int)length{
    int index = self.handle_index.intValue;
    
    if (self.length<index+length) {
        return nil;
    }
    NSData *dat = [self subdataWithRange:NSMakeRange(self.handle_index.intValue, length)];
    self.handle_index = @(self.handle_index.intValue + length);
    return dat;
}

- (void)resetHandleIndex2Zero{
    self.handle_index = @(0);
}




@end
